package com.agent.rag.utils;

import com.agent.commons.utils.MinIOUtil;
import com.agent.rag.service.RagService;
import jakarta.annotation.Resource;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.RegEx;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 文档数据提取工具类
 */
@Component
public class FileUtil {
    private static RagService ragService;
    @Autowired
    public FileUtil(RagService ragService){
        FileUtil.ragService =ragService;
    }
    private static final String pathUrl="http://116.62.7.209:9000/picture/";

    /**
     * 处理新版word文件
     * @param fis
     * @return
     */
    public static String docxConvert(InputStream fis){
        StringBuilder markdown=new StringBuilder();
        try {
            XWPFDocument document = new XWPFDocument(fis);
            List<IBodyElement> bodyElements = document.getBodyElements();
            int picIndex = 0;
            for (IBodyElement element : bodyElements) {
                if (element instanceof XWPFParagraph) {
                    XWPFParagraph para = (XWPFParagraph) element;
                    List<XWPFRun> runs = para.getRuns();
                    markdown.append(para.getText()).append("\n");
                    for (XWPFRun run : runs) {
                        List<XWPFPicture> pictures = run.getEmbeddedPictures();
                        for (XWPFPicture pic : pictures) {
                            String imgName = "image" + picIndex++ + ".png";
                            ByteArrayInputStream in = new ByteArrayInputStream(pic.getPictureData().getData());
                            //存储图片
                            String url = MinIOUtil.uploadFile("picture", in, imgName);
                            String allUrl=pathUrl+url;
                            //返回存储图片的UUID
                            String uuid = ragService.writePicture(allUrl);
                            markdown.append("![图片](").append(uuid).append("http://116.62.7.209:9000/picture/"+url).append(")\n");
                        }
                    }
                } else if (element instanceof XWPFTable) {
                    // 可递归处理表格中单元格的段落/图片
                    XWPFTable table = (XWPFTable) element;
                    for (XWPFTableRow row : table.getRows()) {
                        for (XWPFTableCell cell : row.getTableCells()) {
                            List<XWPFParagraph> cellParagraphs = cell.getParagraphs();
                            for (XWPFParagraph cellPara : cellParagraphs) {
                                markdown.append(cellPara.getText()).append("\n");
                                List<XWPFRun> cellRuns = cellPara.getRuns();
                                for (XWPFRun cellRun : cellRuns) {
                                    List<XWPFPicture> cellPictures = cellRun.getEmbeddedPictures();
                                    for (XWPFPicture pic : cellPictures) {
                                        markdown.append("![图片]()");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return markdown.toString();
    }

    /**
     * 处理旧版word文件
     * @param file
     * @return
     */
    public String docConvert(File file) {
        StringBuilder markdown = new StringBuilder();

        try (FileInputStream fis = new FileInputStream(file);
             HWPFDocument document = new HWPFDocument(fis)) {

            Range range = document.getRange();
            List<Picture> pictures = document.getPicturesTable().getAllPictures();

            int picIndex = 0;

            for (int i = 0; i < range.numParagraphs(); i++) {
                Paragraph para = range.getParagraph(i);
                String text = para.text().trim();
                CharacterRun run = para.getCharacterRun(0);

                // 检查是否是图片段落
                if (document.getPicturesTable().hasPicture(run)) {
                    Picture pic = pictures.get(picIndex++);
                    String imgName = "image" + picIndex + ".png";
                    ByteArrayInputStream in=new ByteArrayInputStream(pic.getContent());
                    String string = MinIOUtil.uploadFile("picture", in, imgName);
                    markdown.append("![图片](").append("http://116.62.7.209:9000/picture/"+string).append(")\n\n");

                } else {
                    markdown.append(text).append("\n\n");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return markdown.toString();
    }
}
